
/**
 * 给枚举值添加前缀，变成${prefix}_${value}的格式
 * *只能用在值是数字的枚举上
 * @param e //枚举
 * @param prefix //前缀
 * @param canRepeatSet //是否允许重复设置
 */
export function setEnumPrefix(e: any, prefix: string | number, canRepeatSet = false) {
    /*@ts-ignore */
    if (!setEnumPrefix.preFixMap) {
        /*@ts-ignore */
        setEnumPrefix.preFixMap = {}
    }
    /*@ts-ignore */
    if (!canRepeatSet && setEnumPrefix.preFixMap[prefix]) {
        console.error(e, prefix);
        throw new Error("枚举前缀重复");
    }
    /*@ts-ignore */
    setEnumPrefix.preFixMap[prefix] = e

    let keys = Object.keys(e).filter(key => typeof e[key] === "number")
    keys.forEach(key => {
        const value = e[key]
        const newValue = `${prefix}_${value}`
        Reflect.deleteProperty(e, value)
        e[key] = newValue
        e[newValue] = key
    })
}

/**延时 */
export function delay(ms: number) {
    return new Promise((r) => {
        setTimeout(() => {
            r(null)
        }, ms);
    })
}

/**
 * 防暴击
 * @param delay 
 * @returns 
 */
export function debounce(delay = 500, immediate = true) {
    let timer: any = null;
    return function (target, key, descriptor: PropertyDescriptor) {
        const method = descriptor.value;
        descriptor.value = function (...args) {
            if (timer) {
                clearTimeout(timer);
            }
            if (immediate) {
                if (!timer) method.call(this, ...args);
                timer = setTimeout(() => {
                    timer = null
                }, delay)
            } else {
                timer = setTimeout(() => {
                    method.call(this, ...args);
                }, delay);
            }
        };
    };
}